package com.example.lenovo.weiyi;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.com.ruanmeng.demon.CommonM;
import com.com.ruanmeng.demon.PerMessM;
import com.com.ruanmeng.demon.TouXiangM;
import com.com.ruanmeng.utils.CommonUtil;
import com.com.ruanmeng.utils.ImgDataUtil;
import com.com.ruanmeng.utils.PreferencesUtils;
import com.com.ruanmeng.utils.Utils;
import com.com.ruanmeng.view.CircleImageView;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.ActionSheetDialog;
import com.yolanda.nohttp.FileBinary;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.rest.Request;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import nohttp.CallServer;
import nohttp.CustomHttpListener;
import share.Const;
import share.HttpIP;

/**
 * Created by Administrator on 2017/5/5.
 */

public class PersonalDataActivity extends BaseActivity {
    @BindView(R.id.imv_lay_back)
    ImageView imvLayBack;
    @BindView(R.id.tv_lay_title)
    TextView tvLayTitle;
    @BindView(R.id.tv_lay_next)
    TextView tvLayNext;
    @BindView(R.id.iv_touxiang)
    CircleImageView ivTouxiang;
    @BindView(R.id.ll_my_touxiang)
    LinearLayout llMyTouxiang;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.ll_my_name)
    LinearLayout llMyName;
    @BindView(R.id.tv_sex)
    TextView tvSex;
    @BindView(R.id.ll_sex)
    LinearLayout llSex;
    @BindView(R.id.tv_my_danwei)
    TextView tvMyDanwei;
    @BindView(R.id.ll_danwei)
    LinearLayout llDanwei;
    @BindView(R.id.tv_my_email)
    TextView tvMyEmail;
    @BindView(R.id.ll_my_email)
    LinearLayout llMyEmail;
    @BindView(R.id.tv_my_age)
    TextView tvMyAge;
    @BindView(R.id.ll_my_age)
    LinearLayout llMyAge;
    @BindView(R.id.tv_my_height)
    TextView tvMyHeight;
    @BindView(R.id.ll_my_height)
    LinearLayout llMyHeight;
    @BindView(R.id.tv_my_weight)
    TextView tvMyWeight;
    @BindView(R.id.ll_my_weight)
    LinearLayout llMyWeight;
    protected static final int CHOOSE_PICTURE = 0;
    protected static final int TAKE_PICTURE = 1;
    private static final int CROP_SMALL_PICTURE = 2;
    protected static Uri tempUri;
    @BindView(R.id.tv_view)
    TextView tvView;
    @BindView(R.id.iv_sex)
    ImageView ivSex;
    @BindView(R.id.ll_sex_content)
    LinearLayout llSexContent;
    @BindView(R.id.tv_my_fbm)
    TextView tvMyFbm;
    @BindView(R.id.ll_fbm)
    LinearLayout llFbm;
    @BindView(R.id.tv_my_sbmi)
    TextView tvMySbmi;
    @BindView(R.id.ll_sbm)
    LinearLayout llSbm;
    @BindView(R.id.tv_my_tbm)
    TextView tvMyTbm;
    @BindView(R.id.ll_tbm)
    LinearLayout llTbm;
    @BindView(R.id.tv_my_qcard)
    TextView tvMyQcard;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    private Intent intent;
    private LinearLayout ll_girl;
    private LinearLayout ll_boy;
    private LinearLayout ll_cancel_pop;
    private int sex;
    private PerMessM model;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personaldata);
        ButterKnife.bind(this);
        AddActivity(this);
        ChangLayTitle("个人资料");
        checkStoragePermission();
        checkReadPermission();
        getData();
    }

    private void getData() {
        Request<String> mRequest = NoHttp.createStringRequest(HttpIP.PerMess, Const.POST);
        mRequest.addHeader("token", PreferencesUtils.getString(PersonalDataActivity.this, "uid"));
        CallServer.getRequestInstance().add(PersonalDataActivity.this, 0, mRequest,
                new CustomHttpListener(PersonalDataActivity.this, true, PerMessM.class) {
                    @Override
                    public void doWork(Object data, boolean isOne) {
                        model = ((PerMessM) data);
                        ImgDataUtil.loadPerImage(PersonalDataActivity.this, HttpIP.Base_IpIMage + model.getObject().getUserhead(), ivTouxiang);
                        tvName.setText(model.getObject().getUserName());
                        //性别  1男
                        llSexContent.setVisibility(View.VISIBLE);
                        if (model.getObject().getSex() == 1) {
                            ivSex.setImageDrawable(getResources().getDrawable(R.drawable.gender_boy));
                            tvSex.setText("男");
                        } else {
                            ivSex.setImageDrawable(getResources().getDrawable(R.drawable.gender_girl));
                            tvSex.setText("女");
                        }
                        tvMyDanwei.setText(model.getObject().getCompName());
                        tvMyEmail.setText(model.getObject().getEmail());
                        //部门
                        tvMyFbm.setText(model.getObject().getDeptName());
                        //年纪
                        tvMyAge.setText(model.getObject().getAge() + "");
                        //身份证
                        tvMyQcard.setText(model.getObject().getCardNo());
                        //身高
                        tvMyHeight.setText(model.getObject().getStature() + "cm");
                        //体重
                        tvMyWeight.setText(model.getObject().getWeight() + "kg");
                        //电话
                        tvPhone.setText(setphone(model.getObject().getMobile()));
                        if(model.getObject().getIsCompany()==0){
                            llFbm.setVisibility(View.GONE);
                            llDanwei.setVisibility(View.GONE);
                        }else {
                            llFbm.setVisibility(View.VISIBLE);
                            llDanwei.setVisibility(View.VISIBLE);
                        }
                    }

                    @Override
                    public void onFinally(JSONObject obj) throws JSONException {
                        super.onFinally(obj);
                    }
                }, true, true);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(PreferencesUtils.getString(PersonalDataActivity.this, "user_name"))) {
            tvName.setText(PreferencesUtils.getString(PersonalDataActivity.this, "user_name"));
        }
        if (!TextUtils.isEmpty(PreferencesUtils.getString(PersonalDataActivity.this, "danwei"))) {
            tvMyDanwei.setText(PreferencesUtils.getString(PersonalDataActivity.this, "danwei"));
        }
        if (!TextUtils.isEmpty(PreferencesUtils.getString(PersonalDataActivity.this, "bumen"))) {
            tvMyFbm.setText(PreferencesUtils.getString(PersonalDataActivity.this, "bumen"));
        }
        if (!TextUtils.isEmpty(PreferencesUtils.getString(PersonalDataActivity.this, "email"))) {
            tvMyEmail.setText(PreferencesUtils.getString(PersonalDataActivity.this, "email"));
        }
        if (!TextUtils.isEmpty(PreferencesUtils.getString(PersonalDataActivity.this, "age"))) {
            tvMyAge.setText(PreferencesUtils.getString(PersonalDataActivity.this, "age"));
        }
        if (!TextUtils.isEmpty(PreferencesUtils.getString(PersonalDataActivity.this, "qcard"))) {
            tvMyQcard.setText(PreferencesUtils.getString(PersonalDataActivity.this, "qcard"));
        }
        if (!TextUtils.isEmpty(PreferencesUtils.getString(PersonalDataActivity.this, "stature"))) {
            tvMyHeight.setText(PreferencesUtils.getString(PersonalDataActivity.this, "stature") + "cm");
        }
        if (!TextUtils.isEmpty(PreferencesUtils.getString(PersonalDataActivity.this, "weight"))) {
            tvMyWeight.setText(PreferencesUtils.getString(PersonalDataActivity.this, "weight") + "kg");
        }
    }

    @OnClick({R.id.ll_my_touxiang, R.id.ll_my_name, R.id.ll_sex, R.id.ll_danwei, R.id.ll_my_email, R.id.ll_my_age, R.id.ll_fbm, R.id.ll_my_qcard, R.id.ll_my_height, R.id.ll_my_weight,R.id.ll_my_phone})
    public void onClick(View view) {
        Intent in;
        switch (view.getId()) {
            case R.id.ll_my_touxiang:
                ActionSheetDialog();
                break;
            case R.id.ll_my_name:
                in = new Intent(PersonalDataActivity.this, ChangeNameActivity.class);
                in.putExtra("name", tvName.getText().toString());
                startActivity(in);
                break;
            case R.id.ll_sex:
//                ShowPopSelectSex();
                break;
            case R.id.ll_danwei:
                in = new Intent(PersonalDataActivity.this, ChangeDanWeiActivity.class);
                in.putExtra("dw", tvMyDanwei.getText().toString());
                startActivity(in);
                break;
            case R.id.ll_my_email:
                in = new Intent(PersonalDataActivity.this, ChangeEmailActivity.class);
                in.putExtra("email", tvMyEmail.getText().toString());
                startActivity(in);
                break;
            case R.id.ll_my_age:
//                in = new Intent(PersonalDataActivity.this, ChangeAgeActivity.class);
//                in.putExtra("age", tvMyAge.getText().toString());
//                startActivity(in);
                break;
            case R.id.ll_my_height:
                in = new Intent(PersonalDataActivity.this, ChangeHeightActivity.class);
                in.putExtra("hight", model.getObject().getStature());
                startActivity(in);
                break;
            case R.id.ll_my_weight:
                in = new Intent(PersonalDataActivity.this, ChangeWeightActivity.class);
                in.putExtra("tz", model.getObject().getWeight());
                startActivity(in);
                break;
            case R.id.ll_fbm://部门
                in = new Intent(PersonalDataActivity.this, ChangeBMActivity.class);
                in.putExtra("bm", tvMyFbm.getText().toString());
                startActivity(in);
                break;
            case R.id.ll_my_qcard://身份证
//                in = new Intent(PersonalDataActivity.this, ChangeQCardActivity.class);
//                in.putExtra("qcard", tvMyQcard.getText().toString());
//                startActivity(in);
                break;
            case R.id.ll_my_phone://修改电话
                in = new Intent(PersonalDataActivity.this, ChangePhonePswActivity.class);
                startActivity(in);
                break;
        }
    }

    /**
     * 选择性别
     */
    private void ShowPopSelectSex() {
        // 加载布局
        LayoutInflater inflater = LayoutInflater
                .from(PersonalDataActivity.this);
        View v = inflater.inflate(R.layout.sex_selector_pop_layout, null);
        ll_girl = (LinearLayout) v.findViewById(R.id.ll_girl);
        ll_boy = (LinearLayout) v.findViewById(R.id.ll_boy);
        ll_cancel_pop = (LinearLayout) v.findViewById(R.id.ll_cancel_pop);
        // 创建popupwindow对话框
        final PopupWindow pop = new PopupWindow(v, LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT);
        pop.setFocusable(true);// 必须有，因为要获得焦点进行输入
        // 设置此参数，点击外边可消失
        pop.setBackgroundDrawable(new BitmapDrawable());
        // 点击其他除了popupwindow对话框的地方就可使popupwindow对话框消失
        pop.setOutsideTouchable(true);
        pop.showAtLocation(tvView, Gravity.CENTER, 0, 0);// 显示位置以某控件为中心
        ll_girl.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                //TODO  请求成功之后设置
                sex = 0;
                getChangeData();
                pop.dismiss();
            }
        });

        ll_boy.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                sex = 1;
                getChangeData();
                pop.dismiss();
            }
        });
        ll_cancel_pop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop.dismiss();
            }
        });
    }

    /**
     * 弹出选照片Dialog
     */
    private void ActionSheetDialog() {
        final String[] stringItems = {"拍照", "从图库选择"};
        final ActionSheetDialog dialog = new ActionSheetDialog(PersonalDataActivity.this, stringItems, null);
        dialog.title("请选择上传方式")
                .titleTextSize_SP(16f)
                .itemTextColor(getResources().getColor(R.color.FirstGrayColor))//字体颜色
                .cancelText(getResources().getColor(R.color.SeconedGrayColor))//取消按钮字体颜色
                .show();

        dialog.setOnOperItemClickL(new OnOperItemClickL() {
            @Override
            public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case CHOOSE_PICTURE: // 选择本地照片
                        Intent openCameraIntent = new Intent(
                                MediaStore.ACTION_IMAGE_CAPTURE);
                        tempUri = Uri.fromFile(new File(Environment
                                .getExternalStorageDirectory(), "image.jpg"));
                        // 指定照片保存路径（SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换
                        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
                        startActivityForResult(openCameraIntent, TAKE_PICTURE);
                        break;
                    case TAKE_PICTURE: // 拍照
                        Intent intent = new Intent(
                                Intent.ACTION_PICK,
                                MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        intent.setDataAndType(
                                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                                "image/*");
                        startActivityForResult(intent, CHOOSE_PICTURE);// //适用于4.4及以上android版本
                        break;
                }
                dialog.dismiss();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) { // 如果返回码是可以用的
            switch (requestCode) {
                case TAKE_PICTURE:
                    startPhotoZoom(tempUri); // 开始对图片进行裁剪处理
                    break;
                case CHOOSE_PICTURE:
                    startPhotoZoom(data.getData()); // 开始对图片进行裁剪处理
                    break;
                case CROP_SMALL_PICTURE:
                    if (data != null) {
                        setImageToView(data); // 让刚才选择裁剪得到的图片显示在界面上
                    }
                    break;
            }
        }
    }

    /**
     * 裁剪图片方法实现
     */
    protected void startPhotoZoom(Uri uri) {
        tempUri = uri;
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        Uri cropUri = Uri.fromFile(new File(
                Environment.getExternalStorageDirectory().getPath() + "/crop.png"));
        intent.putExtra(MediaStore.EXTRA_OUTPUT, cropUri);
        startActivityForResult(intent, CROP_SMALL_PICTURE);
    }

    /**
     * 保存裁剪之后的图片数据
     */
    protected void setImageToView(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            photo = Utils.toRoundBitmap(photo, tempUri); // 这个时候的图片已经被处理成圆形的了
            ivTouxiang.setImageBitmap(photo);
            uploadPic(photo);
        }
    }

    private void uploadPic(Bitmap photo) {
        mRequest = NoHttp.createStringRequest(HttpIP.TouXiang, Const.POST);
        mRequest.addHeader("token", PreferencesUtils.getString(PersonalDataActivity.this, "uid"));
        mRequest.add("userhead", new FileBinary(new File(Environment.getExternalStorageDirectory().getPath() + "/crop.png")));
//        mRequest.add("userhead", new FileBinary(new File(Environment.getExternalStorageDirectory().getPath() + "/crop.png")));
        CallServer.getRequestInstance().add(PersonalDataActivity.this, 0, mRequest,
                new CustomHttpListener(PersonalDataActivity.this, true, TouXiangM.class) {
                    @Override
                    public void doWork(Object data, boolean isOne) {
                        TouXiangM changeHeadM = (TouXiangM) data;
                        ImgDataUtil.loadImage(PersonalDataActivity.this, HttpIP.Base_IpIMage + changeHeadM.getObject(), ivTouxiang);
//                        ImageLoader.getInstance().displayImage(HttpIP.Base_IpIMage + changeHeadM.getObject(), ivTouxiang);
                        PreferencesUtils.putString(PersonalDataActivity.this, "url", changeHeadM.getObject());
                    }

                    @Override
                    public void onFinally(JSONObject obj) throws JSONException {
                        super.onFinally(obj);
                        CommonUtil.showToask(PersonalDataActivity.this, obj.getString("msg"));
                    }
                }, true, true);
    }
    //关于系统6.0以上的权限适配（这里是相机的权限）注意Manifest的导包

    private void checkStoragePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
            if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
                // 是否需要弹出一个解释申请该权限的提示给用户，如果为true，则可以弹。
                if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
                    Toast.makeText(this, "没权限", Toast.LENGTH_SHORT).show();
                    ActivityCompat.requestPermissions(
                            PersonalDataActivity.this,
                            new String[]{Manifest.permission.CAMERA},
                            0);
                } else {
                    // 在Fragment中申请权限，不要使用ActivityCompat.requestPermissions,
                    // 直接使用Fragment的requestPermissions方法，否则会回调到Activity的 onRequestPermissionsResult
                    ActivityCompat.requestPermissions(
                            this,
                            new String[]{Manifest.permission.CAMERA},
                            0);

                    // Const.LOCATION_REQUEST is an app-defined int constant.
                    // The callback method gets the result of the request.
                }

            }
        }
    }

    //关于系统6.0以上的权限适配注意Manifest的导包  读写权限

    private void checkReadPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
            if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
                // 是否需要弹出一个解释申请该权限的提示给用户，如果为true，则可以弹。
                if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                    Toast.makeText(PersonalDataActivity.this, "没权限", Toast.LENGTH_SHORT).show();
                    ActivityCompat.requestPermissions(
                            PersonalDataActivity.this,
                            new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                            0);
                } else {

                    // 在Fragment中申请权限，不要使用ActivityCompat.requestPermissions,
                    // 直接使用Fragment的requestPermissions方法，否则会回调到Activity的 onRequestPermissionsResult
                    ActivityCompat.requestPermissions(
                            PersonalDataActivity.this,
                            new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                                    Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            0);

                    // Const.LOCATION_REQUEST is an app-defined int constant.
                    // The callback method gets the result of the request.
                }

            }
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 0: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                } else {
                    Toast.makeText(this, "请求权限被拒绝，请重新开启权限", Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    /**
     * 修改个人资料
     */
    private void getChangeData() {
        Request<String> mRequest = NoHttp.createStringRequest(HttpIP.UpdatePerMess, Const.POST);
        mRequest.addHeader("token", PreferencesUtils.getString(PersonalDataActivity.this, "uid"));
        mRequest.add("sex", sex);//1  男
        CallServer.getRequestInstance().add(PersonalDataActivity.this, 0, mRequest,
                new CustomHttpListener(PersonalDataActivity.this, true, CommonM.class) {

                    @Override
                    public void doWork(Object data, boolean isOne) {
                        CommonM model = ((CommonM) data);
                        if (sex != 1) {
                            llSexContent.setVisibility(View.VISIBLE);
                            ivSex.setImageDrawable(getResources().getDrawable(R.drawable.gender_girl));
                            tvSex.setText("女");
                        } else {
                            llSexContent.setVisibility(View.VISIBLE);
                            ivSex.setImageDrawable(getResources().getDrawable(R.drawable.gender_boy));
                            tvSex.setText("男");
                        }
                    }

                    @Override
                    public void onFinally(JSONObject obj) throws JSONException {
                        super.onFinally(obj);
                        if (!("100").equals(obj.getString("msgcode"))) {
                            CommonUtil.showToask(PersonalDataActivity.this, obj.getString("msg"));
                        }
                    }
                }, true, true);
    }

    /**
     * 手机号*显示
     */
    public String setphone(String phone_str) {
        StringBuilder sb = new StringBuilder();
        if (!TextUtils.isEmpty(phone_str) && phone_str.length() > 6) {
            for (int i = 0; i < phone_str.length(); i++) {
                char c = phone_str.charAt(i);
                if (i >= 3 && i <= 6) {
                    sb.append('*');
                } else {
                    sb.append(c);
                }
            }
        }
        return sb.toString();
    }
}
